/*
 * Copyright (C) 2021 Huawei Device Co., Ltd.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.example.distschedule.slice;

import com.alibaba.fastjson.JSONObject;
import com.example.distschedule.ResourceTable;
import com.example.distschedule.bean.NetConfigInfo;
import com.example.distschedule.utils.CommandUtil;
import com.example.distschedule.utils.CommonUtil;
import com.socks.library.KLog;
import com.xuhao.didi.core.iocore.interfaces.IPulseSendable;
import com.xuhao.didi.core.iocore.interfaces.ISendable;
import com.xuhao.didi.core.pojo.OriginalData;
import com.xuhao.didi.socket.client.impl.client.action.ActionDispatcher;
import com.xuhao.didi.socket.client.sdk.OkSocket;
import com.xuhao.didi.socket.client.sdk.client.ConnectionInfo;
import com.xuhao.didi.socket.client.sdk.client.OkSocketOptions;
import com.xuhao.didi.socket.client.sdk.client.action.SocketActionAdapter;
import com.xuhao.didi.socket.client.sdk.client.connection.IConnectionManager;
import com.xuhao.didi.socket.client.sdk.client.connection.NoneReconnect;
import ohos.aafwk.ability.AbilitySlice;
import ohos.aafwk.content.Intent;
import ohos.aafwk.content.Operation;
import ohos.agp.components.TextField;
import ohos.eventhandler.EventHandler;
import ohos.eventhandler.EventRunner;
import org.apache.commons.lang3.StringUtils;

public class SocketNetConfigSlice extends AbilitySlice {
    private static final int REQUEST_CODE = 1; // Any positive integer.
    private static final String DEVICE_SERVER_IP = "192.168.51.1";
    private static final int DEVICE_SERVER_PORT = 8686;
    private TextField tfSsid;
    private TextField tfPassword;
    private String originalSsid;
    private String deviceId;

    @Override
    public void onStart(Intent intent) {
        super.onStart(intent);
        super.setUIContent(ResourceTable.Layout_ability_net_config);
        originalSsid = intent.getStringParam("originalSsid");
        deviceId = intent.getStringParam("deviceId");
        initComponents();
    }

    /**
     * socket长连接使用方法
     */
    private void initSocket() {
        EventHandler mHandler = new EventHandler(EventRunner.getMainEventRunner());
        ConnectionInfo mInfo = new ConnectionInfo(DEVICE_SERVER_IP, DEVICE_SERVER_PORT);
        OkSocketOptions mOkOptions = new OkSocketOptions.Builder()
                .setReconnectionManager(new NoneReconnect())
                .setConnectTimeoutSecond(3)
                .setCallbackThreadModeToken(new OkSocketOptions.ThreadModeToken() {
                    @Override
                    public void handleCallbackEvent(ActionDispatcher.ActionRunnable runnable) {
                        mHandler.postTask(runnable);
                    }
                })
                .build();
        IConnectionManager mManager = OkSocket.open(mInfo).option(mOkOptions);

        SocketActionAdapter adapter = new SocketActionAdapter() {
            @Override
            public void onSocketConnectionSuccess(ConnectionInfo info, String action) {
                KLog.i(getString(ResourceTable.String_log_tag),"onSocketConnectionSuccess:" + action );
                //成功
                NetConfigInfo netConfigInfo = new NetConfigInfo(tfSsid.getText(), tfPassword.getText());
                mManager.send(netConfigInfo);
                KLog.i(getString(ResourceTable.String_log_tag),netConfigInfo );
            }

            @Override
            public void onSocketDisconnection(ConnectionInfo info, String action, Exception e) {
                // 断开
                KLog.i(getString(ResourceTable.String_log_tag),action);
                // 跳转
                CommonUtil.judgeDevice(getContext(),deviceId,null);
            }

            @Override
            public void onSocketConnectionFailed(ConnectionInfo info, String action, Exception e) {
                //连接失败
                 KLog.i(getString(ResourceTable.String_log_tag),action);
                mManager.disconnect();
            }

            @Override
            public void onSocketReadResponse(ConnectionInfo info, String action, OriginalData data) {
                //从服务器读取到字节回调
                mManager.disconnect();
                KLog.i(getString(ResourceTable.String_log_tag),action);
                JSONObject respond = (JSONObject) JSONObject.parse(data.getBodyBytes());
            }

            @Override
            public void onSocketWriteResponse(ConnectionInfo info, String action, ISendable data) {
                //写给服务器字节后回调
                KLog.i(getString(ResourceTable.String_log_tag),action);
            }

            @Override
            public void onPulseSend(ConnectionInfo info, IPulseSendable data) {
                //发送心跳后的回调
                KLog.i(getString(ResourceTable.String_log_tag),info);
            }

        };
        mManager.registerReceiver(adapter);
        mManager.connect(); //连接
    }

    private void initComponents() {
        findComponentById(ResourceTable.Id_net_text_other_network).setClickedListener(component -> {
            presentForResult(new OtherWifiSlice(), new Intent(), REQUEST_CODE);
        });
        tfSsid = (TextField) findComponentById(ResourceTable.Id_net_tf_ssid);
        tfPassword = (TextField) findComponentById(ResourceTable.Id_net_tf_password);
        if (!StringUtils.isEmpty(originalSsid)){
            tfSsid.setText(originalSsid);
        }

        findComponentById(ResourceTable.Id_net_button_ok).setClickedListener(component -> {
            initSocket();
        });
        findComponentById(ResourceTable.Id_net_img_back).setClickedListener(component -> {
            onBackPressed();
        });
    }

    private void toControlDevice(String abilityName){
        Intent intent = new Intent();
        Operation operation = new Intent.OperationBuilder()
                .withBundleName(getBundleName())
                .withAbilityName(abilityName)
                .build();
        intent.setOperation(operation);
        intent.setParam("deviceId",deviceId);
        startAbility(intent);
        terminateAbility();
    }

    @Override
    public void onActive() {
        super.onActive();
    }

    /**
     * otherWifi页面回调结果
     */
    @Override
    protected void onResult(int requestCode, Intent resultIntent) {
        KLog.i("onResult onResult==");
        switch (requestCode) {
            case REQUEST_CODE: {
                String resultSsid = resultIntent.getStringParam("ssid");
                if (!StringUtils.isEmpty(resultSsid)){
                    tfSsid.setText(resultSsid);
                }
                break;
            }
            default: {
                break;
            }
        }
    }

    @Override
    public void onForeground(Intent intent) {
        super.onForeground(intent);
    }
}
